#include "OrderRecord.h"

#include <QDebug>

OrderRecord::OrderRecord() :
    ASTM()
{
}

OrderRecord::OrderRecord(const QString &sampleId, const QString &sampleType, const QDateTime &sampleTime) :
    ASTM()
{
    this->sampleID = sampleId;
    this->projectName = "NULL"; //仪器向LIS发送结果时为NULL，检测项目由结果(R)提供
    this->sampleType = sampleType;
    requestedDateTime = sampleTime.toString("yyyyMMddHHmmss");
}

QString OrderRecord::buildRecord() const
{
    QString record = recordTypeSymbol(RecordType::Order);
    record += FIELD;
    record += QString::number(frameIndex);
    record += FIELD;
    record += sampleID;
    record += FIELD;
    record += projectName;
    record += FIELD;
    //最多两位小数
    record += QString::number(dilutionRate, 10, 2);
    record += FIELD;
    record += QString::number(repeatNum);
    record += FIELD;
    record += requestedDateTime;
    record += FIELD;
    record += sampleType;
    record += FIELD;
    record += applyTypeList.value(applyType);
    record += CR;

    for(auto &resut: results) {
        record += resut.buildRecord();
    }

    return record;
}

bool OrderRecord::analyzeRecord(const QString &str)
{
    QStringList fields = str.split(FIELD);

    if(fields.count() < 9 || fields.value(0) != recordTypeSymbol(RecordType::Order)) {
        // qWarning() << "HeaderRecord: Syntax Error!";
        return false;
    }

    bool ok = false;
    frameIndex = fields[1].toInt(&ok);
    if(!ok) {
        frameIndex = 1;
    }

    sampleID = fields[2];
    projectName = fields[3];
    dilutionRate = fields[4].toDouble();
    repeatNum = fields[5].toInt();
    requestedDateTime = fields[6];
    sampleType = fields[7];
    // if(sampleTypeList.indexOf(fields[7]) >= 0)
    //     sampleType = static_cast<SampleType>(sampleTypeList.indexOf(fields[7]));
    if(applyTypeList.indexOf(fields[8]) >= 0)
        applyType = static_cast<ApplyType>(applyTypeList.indexOf(fields[8]));

    return true;
}

void OrderRecord::addResult(const ResultRecord &result)
{
    int resultFrameIndex = results.count() + 1;

    results << result;
    results.last().frameIndex = resultFrameIndex;
}
